package cn.tedu.erp.project.security;

import cn.tedu.erp.project.mapper.AdminMapper;
import cn.tedu.erp.project.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //接收从表单传过来的数据,和数据库中的进行对比,如果不存在返回null
        log.debug("spring security框架调用了loadUserByUsername方法,参数:{}", s);
        AdminLoginInfoVO loginInfoVO = mapper.getLoginInfoByUsername(s);
        log.debug("从数据库中根据用户名[{}]查询登录信息,结果:{}", s, loginInfoVO);
        if (loginInfoVO == null) {
            return null;
        }
        List<GrantedAuthority> authorities = new ArrayList<>();//权限列表
        List<String> permissions = loginInfoVO.getPermissions();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        AdminDetails adminDetails = new AdminDetails(
                loginInfoVO.getId(),
                loginInfoVO.getUsername(),
                loginInfoVO.getPassword(),
                loginInfoVO.getEnable() == 1,
                authorities
        );
        //存在则返回userdetails对象,对象包含用户的信息
        log.debug("即将向spring security返回userdetails类型的对象,{}", adminDetails);
        return adminDetails;
    }
}
